<template>
  <div class="ccui-app-container contract-approval">
    <!-- 高级搜索 -->
    <div class="ccui-advanced-search-wrapper ccui-clearfix">
      <!-- 全部 -->
      <el-search
        v-show="isFocus === 'all'"
        ref="search"
        :formProp="formData"
        @search="search"
        @change="change"
        :isShowSearch="true"
        :selectClear="true"
        :isShow="true"
        class="ccui-highsearch"
      >
        <anchorTitle
          isList
          :totalNum="totalNum"
          :tabBtn="tableTopBtn"
          :isFocus="isFocus"
          @tabBtnChange="tableTopChange"
        />
        <template slot="search">
          <el-input
            v-model="formData.contractName"
            clearable
            searchLabel="合同名称"
            placeholder="请输入合同名称模糊查询"
          ></el-input>
        </template>
        <el-input
          v-model="formData.contractCode"
          clearable
          searchLabel="合同编号"
          placeholder="请输入合同编号模糊查询"
          slot="searchItem1"
        ></el-input>
        <el-input
          v-model="formData.formalContractCode"
          clearable
          searchLabel="合同正式编号"
          placeholder="请输入合同正式编号模糊查询"
          slot="searchItem2"
        ></el-input>
        <el-input
          v-model="formData.contractName"
          clearable
          searchLabel="合同名称"
          placeholder="请输入合同名称模糊查询"
          slot="searchItem3"
        ></el-input>
        <el-input
          v-model="formData.partyBName"
          clearable
          searchLabel="供应商1"
          placeholder="请输入供应商1名称模糊查询"
          slot="searchItem4"
        ></el-input>
        <el-input
          v-model="formData.partyBNameBak"
          clearable
          searchLabel="供应商2"
          placeholder="请输入供应商2名称模糊查询"
          slot="searchItem5"
        ></el-input>
        <el-input
          v-model="formData.reportInOrgName"
          clearable
          searchLabel="填报单位"
          placeholder="请输入填报单位模糊查询"
          slot="searchItem6"
        ></el-input>
        <el-select
          class="ccui-form-longInput"
          v-model="formData.currencyCode"
          searchLabel="币种"
          placeholder="请选择币种查询"
          slot="searchItem7"
        >
          <el-option
            v-for="item in currencyList"
            :key="item.dicKey"
            :label="item.dicValue"
            :value="item.dicKey"
          >
          </el-option>
        </el-select>
        <el-date-picker
          v-model="formData.compileDate"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          searchLabel="编制日期"
          slot="searchItem8"
        >
        </el-date-picker>
        <el-input
          v-model="formData.partyAName"
          clearable
          searchLabel="合同签订单位(甲方)"
          placeholder="请输入合同签订单位(甲方)模糊查询"
          slot="searchItem9"
        ></el-input>
        <el-select
          class="ccui-form-longInput"
          v-model="formData.status"
          searchLabel="审批状态"
          placeholder="请选择审批状态查询"
          slot="searchItem10"
        >
          <el-option
            v-for="item in jsList.approvalState"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-select
          class="ccui-form-longInput"
          v-model="formData.businessBillTypes"
          searchLabel="审批类型"
          placeholder="请选择审批类型查询"
          slot="searchItem11"
        >
          <el-option
            v-for="item in jsList.contractType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-search>
      <!-- 待审批 -->
      <el-search
        v-show="isFocus === 'pending'"
        ref="search"
        :formProp="formData"
        @search="search"
        @change="change"
        :isShowSearch="true"
        :selectClear="true"
        :isShow="true"
        class="ccui-highsearch no-print"
      >
        <anchorTitle
          isList
          :totalNum="totalNum"
          :tabBtn="tableTopBtn"
          :isFocus="isFocus"
          @tabBtnChange="tableTopChange"
        />
        <template slot="search">
          <el-input
            v-model="formData.contractName"
            clearable
            searchLabel="合同名称"
            placeholder="请输入合同名称模糊查询"
          ></el-input>
        </template>
        <el-input
          v-model="formData.contractCode"
          clearable
          searchLabel="合同编号"
          placeholder="请输入合同编号模糊查询"
          slot="searchItem1"
        ></el-input>
        <el-input
          v-model="formData.formalContractCode"
          clearable
          searchLabel="合同正式编号"
          placeholder="请输入合同正式编号模糊查询"
          slot="searchItem2"
        ></el-input>
        <el-input
          v-model="formData.contractName"
          clearable
          searchLabel="合同名称"
          placeholder="请输入合同名称模糊查询"
          slot="searchItem3"
        ></el-input>
        <el-input
          v-model="formData.partyBName"
          clearable
          searchLabel="供应商1"
          placeholder="请输入供应商1名称模糊查询"
          slot="searchItem4"
        ></el-input>
        <el-input
          v-model="formData.partyBNameBak"
          clearable
          searchLabel="供应商2"
          placeholder="请输入供应商2名称模糊查询"
          slot="searchItem5"
        ></el-input>
        <el-input
          v-model="formData.reportInOrgName"
          clearable
          searchLabel="填报单位"
          placeholder="请输入填报单位模糊查询"
          slot="searchItem6"
        ></el-input>
        <el-select
          class="ccui-form-longInput"
          v-model="formData.currencyCode"
          searchLabel="币种"
          placeholder="请选择币种查询"
          slot="searchItem7"
        >
          <el-option
            v-for="item in currencyList"
            :key="item.dicKey"
            :label="item.dicValue"
            :value="item.dicKey"
          >
          </el-option>
        </el-select>
        <el-date-picker
          v-model="formData.compileDate"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          searchLabel="编制日期"
          slot="searchItem8"
        >
        </el-date-picker>
        <el-input
          v-model="formData.partyAName"
          clearable
          searchLabel="合同签订单位(甲方)"
          placeholder="请输入合同签订单位(甲方)模糊查询"
          slot="searchItem9"
        ></el-input>
        <el-select
          class="ccui-form-longInput"
          v-model="formData.businessBillTypes"
          searchLabel="审批类型"
          placeholder="请选择审批类型查询"
          slot="searchItem11"
        >
          <el-option
            v-for="item in jsList.contractType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-search>
      <!-- 已审批 -->
      <el-search
        v-show="isFocus === 'approved'"
        ref="search"
        :formProp="formData"
        @search="search"
        @change="change"
        :isShowSearch="true"
        :selectClear="true"
        :isShow="true"
        class="ccui-highsearch no-print"
      >
        <anchorTitle
          isList
          :totalNum="totalNum"
          :tabBtn="tableTopBtn"
          :isFocus="isFocus"
          @tabBtnChange="tableTopChange"
        />
        <template slot="search">
          <el-input
            v-model="formData.contractName"
            clearable
            searchLabel="合同名称"
            placeholder="请输入合同名称模糊查询"
          ></el-input>
        </template>
        <el-input
          v-model="formData.contractCode"
          clearable
          searchLabel="合同编号"
          placeholder="请输入合同编号模糊查询"
          slot="searchItem1"
        ></el-input>
        <el-input
          v-model="formData.formalContractCode"
          clearable
          searchLabel="合同正式编号"
          placeholder="请输入合同正式编号模糊查询"
          slot="searchItem2"
        ></el-input>
        <el-input
          v-model="formData.contractName"
          clearable
          searchLabel="合同名称"
          placeholder="请输入合同名称模糊查询"
          slot="searchItem3"
        ></el-input>
        <el-input
          v-model="formData.partyBName"
          clearable
          searchLabel="供应商1"
          placeholder="请输入供应商1名称模糊查询"
          slot="searchItem4"
        ></el-input>
        <el-input
          v-model="formData.partyBNameBak"
          clearable
          searchLabel="供应商2"
          placeholder="请输入供应商2名称模糊查询"
          slot="searchItem5"
        ></el-input>
        <el-input
          v-model="formData.reportInOrgName"
          clearable
          searchLabel="填报单位"
          placeholder="请输入填报单位模糊查询"
          slot="searchItem6"
        ></el-input>
        <el-select
          class="ccui-form-longInput"
          v-model="formData.currencyCode"
          searchLabel="币种"
          placeholder="请选择币种查询"
          slot="searchItem7"
        >
          <el-option
            v-for="item in currencyList"
            :key="item.dicKey"
            :label="item.dicValue"
            :value="item.dicKey"
          >
          </el-option>
        </el-select>
        <el-date-picker
          v-model="formData.compileDate"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          searchLabel="编制日期"
          slot="searchItem8"
        >
        </el-date-picker>
        <el-input
          v-model="formData.partyAName"
          clearable
          searchLabel="合同签订单位(甲方)"
          placeholder="请输入合同签订单位(甲方)模糊查询"
          slot="searchItem9"
        ></el-input>
        <el-select
          class="ccui-form-longInput"
          v-model="formData.businessBillTypes"
          searchLabel="审批类型"
          placeholder="请选择审批类型查询"
          slot="searchItem11"
        >
          <el-option
            v-for="item in jsList.contractType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-select
          class="ccui-form-longInput"
          v-model="formData.operResultTypes"
          searchLabel="审批结果"
          placeholder="请选择审批结果查询"
          clearable
          slot="searchItem12"
        >
          <el-option
            v-for="item in jsList.operResultTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-search>
    </div>
    <!-- table表格 -->
    <div class="ccui-multifunctional-table-wrapper">
      <el-table
        :data="tableData"
        :fit="true"
        :cell-style="cellStyle"
        border
        class="ccui-multifunctional-table"
        @header-dragend="tableTitleWidth"
        @row-click="handleRowClick"
      >
        <el-table-column label="序号" width="50" fixed>
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <template v-for="(table, index) in tableTheadOptions">
          <el-table-column
            :fixed="table.fixed || false"
            :key="index"
            :label="table.label"
            :min-width="table.width"
            :prop="table.prop"
            :align="table.align || 'left'"
            :header-align="table.headerAlign || 'left'"
            show-overflow-tooltip
          >
          </el-table-column>
        </template>

        <el-table-column
          v-if="isFocus === 'pending'"
          label="操作"
          fixed="right"
        >
          <template slot-scope="{ row }">
            <el-button
              size="mini"
              type="text"
              ref="spsubplan-edit-item"
              @click="goApproval(row)"
              >审批</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="ccui-table-footer" v-show="tableData.length > 0">
        <div id="ccui-paging">
          <el-pagination
            :total="totalNum"
            :page-size="pageSizeCode"
            :current-page="pageNoCode"
            :page-sizes="[10, 20, 50, 100, 200, 500]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            popper-class="ccui-paging-page-size-popper"
            @prev-click="handlePrev"
            @next-click="handleNext"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <el-button
            class="ccui-pagination-btn"
            size="mini"
            type="default"
            @click="handleSizeChange('none')"
            >确定</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import jsList from "../js";
import publicComponent from "@/basa/components/public";
import { postGetEnum } from "@/basa/api";
import { setSessionItem, getSessionItem, proxyDateFormat } from "@/basa/utils";
import { getList } from "../api";

export default {
  components: {
    anchorTitle: publicComponent.anchorTitle
  },
  data() {
    return {
      jsList,
      formData: {},
      draggFlag: true,
      tableName: this.tableList.eqContractApproval, // 表格命名
      // 动态表格
      tableTheadOptions: [],
      // 全选以及页码
      totalNum: 0,
      total: 0,
      pageNoCode: 1,
      pageSizeCode: 10,
      formDataSearch: {},
      localSearchData: {},
      tableData: [],
      // 表格顶部按钮
      tableTopBtn: [
        { label: "全部", value: "all" },
        { label: "待审批", value: "pending" },
        { label: "已审批", value: "approved" }
      ],
      isFocus: "pending",
      approvalState: "pending",
      currencyList: []
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.setTableWidth();
      this.renderTable();
      this.getEnum();
    },

    // 列表数据请求
    getList(reqObj) {
      let obj = {};
      obj = typeof reqObj == "object" ? reqObj : obj;
      obj.pageNo = this.pageNoCode;
      obj.pageSize = this.pageSizeCode;
      obj.type = this.approvalState;
      obj.businessBillTypes = this.formData.businessBillTypes
        ? [this.formData.businessBillTypes]
        : [];

      getList(obj).then(res => {
        if (res.data.data.rows.length) {
          this.tableData = res.data.data.rows.map(n => ({
            ...n,
            businessData: {
              ...n.businessData,
              compileDate: n.businessData.compileDate
                ? proxyDateFormat(n.businessData.compileDate)
                : ""
            }
          }));
        } else {
          this.tableData = [];
        }
        this.totalNum = res.data.data.recordsTotal;
        this.total = res.data.data.recordsTotal;
        this.pageNoCode = res.data.data.pageNo;
      });
    },

    // 获取枚举
    getEnum() {
      postGetEnum("getCurrencyTypeDict").then(res => {
        this.currencyList = res.data.data;
      });
    },

    // 跳转审批
    goApproval({ businessData, todoData, todoData: { businessBillTypeCode } }) {
      this.setBusinessList(todoData);
      const businessList = JSON.stringify(todoData);
      sessionStorage.setItem("businessList", businessList);
      const { id, protocolId, contractName: name } = businessData;
      if (businessBillTypeCode == "S0108") {
        this.$router.push({
          path: "/contractManagement/transportContractApproval/transportContractAgreementDetail",
          query: {
            name,
            concId: id,
            protocolId
          }
        });
        return;
      }
      const jumpUrl = {
        S0105:
          "/contractManagement/transportContractApproval/contractDraftDetail/",
        S0106:
          "/contractManagement/transportContractApproval/contractChangeDetail/"
      };
      this.$router.push({
        path: `${jumpUrl[businessBillTypeCode]}${id}`,
        query: { name }
      });
    },

    // 详情
    goDetail({
      businessData: { id, protocolId },
      todoData: { businessBillTypeCode }
    }) {
      const type = "approval";
      this.setSourceRoute(this.$route.path);
      if (businessBillTypeCode === "S0108") {
        this.$router.push({
          path: "/contractManagement/transportContractAgreement/item-detail",
          query: {
            concId: id,
            protocolId,
            type
          }
        });
        return;
      }
      const jumpUrl = {
        S0105: "/contractManagement/transportContractDraft/item-detail",
        S0106:
          "/contractManagement/transportContractChange/contractChangeDetail"
      };
      this.$router.push({
        path: `${jumpUrl[businessBillTypeCode]}/${id}`,
        query: { type }
      });
    },

    // set 合同访问路径
    setSourceRoute(path) {
      this.setRouteUrl(path);
      setSessionItem("contractDraftSource", "url", path);
    },

    // 根据返回状态显示不同的文字颜色
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (["businessData.contractCode"].includes(column.property)) {
        return { color: "#0089EF", cursor: "pointer" };
      }
    },

    // 行点击事件
    handleRowClick(row, column, event) {
      if (["businessData.contractCode"].includes(column.property)) {
        this.goDetail(row);
      }
    },

    // 顶部按钮切换
    tableTopChange({ value }) {
      this.isFocus = value;
      this.approvalState = value;
      // this.resetFormData();
      this.getList();
    },

    // 重置表单
    // resetFormData() {
    //   this.formData = {
    //     contractName: "",
    //     contractCode: "",
    //     partyBName: "",
    //     partyBNameBak: "",
    //     reportInOrgName: "",
    //     compileDate: "",
    //     partyAName: "",
    //     thirdCategoriesOfName: "",
    //     searchState: ""
    //   };
    //   setSessionItem("pageNo", this.tableName, {
    //     pageNo: 1,
    //     searchForm: {}
    //   });
    //   this.formDataSearch = {};
    //   this.pageNoCode = 1;
    //   this.pageSizeCode = 10;
    // },

    // 默认渲染表格
    renderTable() {
      const localTableData = localStorage.getItem(this.tableName)
        ? JSON.parse(localStorage.getItem(this.tableName))
        : [];
      let unfixedTableThead = jsList.unfixedTableThead.concat(
        jsList.fixedTableThead
      );
      let localTableDataStr = localTableData.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );
      let unfixedTableTheadStr = unfixedTableThead.map(
        ({ label, prop, width, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );

      if (localTableData.length === unfixedTableThead.length) {
        let flag = localTableDataStr.every(item =>
          unfixedTableTheadStr.includes(item)
        );
        if (flag) {
          // 完全相同
          this.tableTheadOptions = localTableData;
          this.tableThead = localTableData;
          jsList.unfixedTableThead = localTableData.filter(item => {
            return !jsList.fixedTableThead.find(
              cItem => item.prop === cItem.prop
            );
          });
        } else {
          // 长度相同但值不同
          this.tableThead = jsList.unfixedTableThead.concat(
            jsList.fixedTableThead
          );
          const comment = JSON.stringify(this.tableThead);
          localStorage.setItem(this.tableName, comment);
          const localTableData = JSON.parse(
            localStorage.getItem(this.tableName)
          );
          this.tableTheadOptions = localTableData;
        }
      } else {
        // 长度不同
        this.tableThead = jsList.unfixedTableThead.concat(
          jsList.fixedTableThead
        );
        const comment = JSON.stringify(this.tableThead);
        localStorage.setItem(this.tableName, comment);
        const localTableData = JSON.parse(localStorage.getItem(this.tableName));
        this.tableTheadOptions = localTableData;
      }
    },
    // 渲染本地存储表格宽度
    setTableWidth() {
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      if (localTableData) {
        for (let i = 0; i < this.tableTheadOptions.length; i++) {
          if (this.tableTheadOptions[i].label === localTableData[i].label) {
            this.tableTheadOptions[i].width = localTableData[i].width;
          }
        }
      }
    },
    // 表格宽度更改存入
    tableTitleWidth(newWidth, oldWidth, column, event) {
      for (let i = 0; i < jsList.unfixedTableThead.length; i++) {
        if (jsList.unfixedTableThead[i].label === column.label) {
          jsList.unfixedTableThead[i].width = newWidth;
        }
      }
      this.tableThead = jsList.unfixedTableThead.concat(jsList.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
      this.draggFlag = false;
      this.$nextTick(() => {
        this.draggFlag = true;
      });
    },
    // 上一页
    handlePrev() {
      --this.pageNoCode;
      this.getList();
    },
    // 下一页
    handleNext() {
      ++this.pageNoCode;
      this.getList();
    },
    // Todo 高级搜索所需函数 start
    search(searchData) {
      this.pageNoCode = 1;
      this.formDataSearch = searchData;
      this.localSearchData = JSON.parse(JSON.stringify(searchData));
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
      this.getList(this.formDataSearch);
    },
    change(index, key, value) {
      const formDataKeys = Object.keys(this.formData);
      formDataKeys.map(_ => {
        if (_ !== key) this.formData[_] = "";
      });
    },
    // 每页条数发生改变
    handleSizeChange(val) {
      this.pageNoCode = 1;
      if (val !== "none") {
        this.pageSizeCode = val;
        setSessionItem("pageSize", this.tableName, val);
      }
      this.getList(this.formDataSearch);
    },
    // 当前页发生改变
    handleCurrentChange(val) {
      let searchFormData = getSessionItem("pageNo", this.tableName) || {};
      setSessionItem("pageNo", this.tableName, {
        pageNo: val,
        searchForm: searchFormData.searchForm || {}
      });
      this.formDataSearch = {
        ...this.formDataSearch,
        ...searchFormData.searchForm
      };
      // 跳转翻页都会调这个方法
      this.pageNoCode = val;
      this.getList(this.formDataSearch);
    },

    ...mapActions(["setRouteUrl", "setBusinessList"])
  },
  activated() {
    if (Object.keys(this.localSearchData).length > 0) {
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
    }
    this.formData = {};
    this.getList();
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (!/-add|-edit|-detail/g.test(from.path)) {
        vm.isFocus = "pending";
        vm.approvalState = "pending";
      }
    });
  }
};
</script>

<style lang="scss" scoped>
/deep/.ccui-advanced-search-wrapper
  .el-search
  .el-searchs-bottom
  .el-form-item
  .el-form-item__label {
  min-width: 126px !important;
}
</style>
